import { Button, Descriptions, Row, Divider, Space, Select, Input, Tooltip,Checkbox } from 'antd'
import { useEffect, useState } from 'react'
// import { queryCodeTableList, updateCodeTable, createCodeTable,deleteCodeTable,queryCodeTableSql,queryCodeTableExec,
//   queryCodeTableTemplateGroupOptions,queryCodeTableTemplateOptions,queryCodeTableCodeFile,queryCodeTableSaveCode,
//   queryCodeTableCodes, queryCodeTableDbTables, queryCodeTableSaveTables, queryCodeTableTemplateGroupBaseDirTree,queryCodeTableDetails } from "../../../services/index"
import apis from "../../../services/index"
import TableApis from "./tableDescriptions/TableApis"

const extendItemsInfo = {
  frontHome: {title: '首页类型', tip: '模型首页类型；list,tree', type:"select", option: [{value: 'list', label: '列表页'}, {value: 'tree', label: '树型页'}]},
  tree: {title: '树型定义', tip: '定义树型结构；生成tree接口，例如：id~title~parent_id', type: "text"},
  option: {title: '选项定义', tip: '定义表选项;生成option接口； 例如： id~title', type: "text"},
  approval: {title: '审批定义', tip: '审核定义；例如：4~id； 4为审批流ID，id为数据唯一识别ID', type: "text"},
  foreign: {title: '外键定义', tip:'定义表的外键', type: 'text'},
  apis: {title: '角色方法', tip: '定义对应角色的控制支持方法', type: 'checkbox',
    options: [
                {value: 'details', label: '详情'},
                {value: 'list', label: '列表'},
                {value: 'create', label: '创建'},
                {value: 'update', label: '更新'},
                {value: 'delete', label: '删除'},
              ]}
};

export default (props) => {
  const {id} = props;
  const [table, setTable] = useState({});
  const [extend, setExtend] = useState({})

  /**
   * 解析扩展数据
   *
   * @param item
   * @returns {[]}
   */
  const parseExtendItems = (item) => {
    let comment = item.comment
    let title = item.title;
    let extendOptions = ""
    let extendItems = []
    if(comment) {
      let parts = comment.split(";")
      if(parts.length>0) {
        //   //title
        title = item.title || parts[0]
        if(parts.length>=2) {
          extendOptions = parts[1]
        }
        if(parts.length>=3) {
          let extendParts = parts[2].split(",")
          for(let i=0; i<extendParts.length; i++) {
            let tmpParts = extendParts[i].split(":")
            console.log(extendParts[i])
            if(tmpParts.length==2) {
              extendItems.push({name: tmpParts[0], value: tmpParts[1]})
            }
          }
        }
      }
    }
    //检查填充option
    if(extendOptions && extendOptions != "") {
      extendItems.push({name:'option', value: extendOptions})
    }
    return extendItems;
  }

  /**
   * 更新表扩展信息
   *
   * @param name
   * @param value
   */
  const updateTableExtend = (name, value) => {
    let items = parseExtendItems(table);
    //去重
    let o = {};
    items.forEach((item)=>{
      o[item.name] = item.value;
    })
    //判断标题
    if(name === 'title') {
      table.title = value;
    } else {
      o[name] = value;
    }
    // let option = o?.option || ''
    // delete o['option'];


    //还原成备注字符串
    // let str = table.title + ';' + option + ';';
    let str = table.title + ';;';

    let extendParts = [];
    Object.keys(o).forEach(key=>{
      extendParts.push(key + ':' + o[key])
    })
    str += extendParts.join(',')

    let tableInfo = {...table, comment: str};
    setTable(tableInfo)
    apis.updateCodeTable(tableInfo)
  }

  useEffect(()=>{
    apis.queryCodeTableDetails({id: id}).then(r=>{
      if(r.code === 2000) {
        setTable(r.payload)
        let items = parseExtendItems(r.payload)
        let o = {};
        items.forEach(v=>{
          o[v.name] = v.value;
        })
        setExtend(o);
      }
    })
  }, [])

  console.log('extend..........', extend)

  return   <>

              <Divider />
              <Row>
                <Descriptions title={table.name}  layout="vertical" bordered>
                  <Descriptions.Item label="ID">{table.id}</Descriptions.Item>
                  <Descriptions.Item label="Name">{table.name}</Descriptions.Item>
                  <Descriptions.Item label="Title"><Tooltip title="字段标题">
                    <Input value={table.title} style={{width: '320px'}} onChange={(e)=>{
                      setTable({...table, title: e.target.value})
                    }} onBlur={(e)=>{
                      updateTableExtend('title', e.target.value);
                    }} />
                  </Tooltip></Descriptions.Item>
                  {extend && Object.keys(extendItemsInfo).map(value => {
                    let item = extendItemsInfo[value];
                    return <Descriptions.Item label={item.title}>
                      {item.type==='select' && <Select defaultValue={extend[value] ?extend[value] : 'list'} options={item.option} onChange={(v)=>{
                        updateTableExtend(value, v);
                      }} />}
                      {item.type==='text' && <Tooltip title={item.tip}>
                        <Input value={extend[value]} style={{width: '320px'}} onChange={(e)=>{
                          setExtend({...extend, [value]: e.target.value})
                        }} onBlur={(e)=>{
                          updateTableExtend(value, e.target.value);
                        }} />
                      </Tooltip>}
                      {item.type==='checkbox' && <TableApis value={extend[value]} onChange={(v)=>{
                        updateTableExtend(value, v);
                      }} />
                      //   <Tooltip title={item.tip}>
                      //   <Input name="name" style={{width: '50px'}} />
                      //   <Checkbox.Group options={item.options} defaultValue={null} onChange={null} />
                      // </Tooltip>
                      }
                    </Descriptions.Item>
                  })}

                  {/*<Descriptions.Item label="comment">*/}
                  {/*  {table.comment}*/}
                  {/*</Descriptions.Item>*/}
                </Descriptions>
              </Row>

  </>
}
